<script setup>
import UserPanel from './UserPanel.vue'
import { ref, computed, onMounted } from 'vue'
import ReconnectingWebSocket from 'reconnecting-websocket'
import { getUserMedia } from '@/utils/UseMedia.js'
import { getHistoryMsg, getList } from '@/api/Communicate.js'
import { UserInfo } from '@/stores'
import Peer from 'peerjs'
// 用户name
const username = ref('')
const userInfo = UserInfo()
username.value = userInfo.username

// 要发送的消息
const sendMessage = ref('')
const ReceiveMessage = ref()

const scrollbarRef = ref()
const innerRef = ref()
const sendDisable = computed(() => sendMessage.value === '')

const connectionState = ref('') // 连接状态
const socket = ref()

const VedioDialog = ref()
// 用户列表信息
const userList = ref([
  {
    name: 'Jokic',
    logo: '#'
  },
  {
    name: '用户2',
    logo: '#'
  },
  {
    name: '用户3',
    logo: '#'
  },
  {
    name: '用户4',
    logo: '#'
  }
])
// 当前聊天用户信息（id, name）
const ResentUser = ref('')
// 与当前用户聊天消息
const Message = ref([
  {
    sender: '用户1',
    receiver: 'cometlie',
    content: '你好'
  },
  {
    sender: 'cometlie',
    receiver: '用户1',
    content: 'hi'
  },
  {
    sender: '用户1',
    receiver: 'cometlie',
    content: '你好'
  },
  {
    sender: 'cometlie',
    receiver: '用户1',
    content: 'hi'
  },
  {
    sender: '用户1',
    receiver: 'cometlie',
    content: '你好'
  },
  {
    sender: 'cometlie',
    receiver: '用户1',
    content: 'hi'
  },
  {
    sender: '用户1',
    receiver: 'cometlie',
    content: '你好'
  },
  {
    sender: 'cometlie',
    receiver: '用户1',
    content: 'hi'
  },
  {
    sender: '用户1',
    receiver: 'cometlie',
    content: '你好'
  },
  {
    sender: 'cometlie',
    receiver: '用户1',
    content: 'hi'
  },
  {
    sender: '用户1',
    receiver: 'cometlie',
    content: '你好'
  },
  {
    sender: 'cometlie',
    receiver: '用户1',
    content: 'hi'
  },
  {
    sender: '用户1',
    receiver: 'cometlie',
    content: '你好'
  },
  {
    sender: 'cometlie',
    receiver: '用户1',
    content: 'hi'
  }
])

// 点击用户
const UserPanelClick = async (name) => {
  ResentUser.value = name
  const res = await getHistoryMsg(username.value, name)
  Message.value = res.data.data
}
// 滚动到底部
const ScrolltoButtom = () => {
  scrollbarRef.value.setScrollTop(1e6)
}

// 发送消息
const sendbtn = () => {
  Message.value.push({
    senderName: username.value,
    receiver: ResentUser.value.name,
    content: sendMessage.value
  })
  const msg = ref()
  msg.value = JSON.stringify({
    sender: username.value,
    target: ResentUser.value,
    msg: sendMessage.value
  })
  socket.value.send(msg.value)
  sendMessage.value = ''
  ScrolltoButtom()
}

//通讯
const centerDialogVisible = ref(false)
const localCameraVideo = ref()
const localUserVideo = ref()
const remoteCameraVideo = ref()

const myPeer = new Peer(username.value)
// 连接websocket服务端
const establishWebSocketConnection = (username) => {
  console.log('开始连接')
  //连接到服务端
  const webSocketConnection = new ReconnectingWebSocket(
    `ws://192.168.70.141:8514/chat/${username}`
  )
  console.log(11)
  // 打开连接
  webSocketConnection.onopen = () => {
    console.log('websocket onopen')
    connectionState.value = `${username}连接服务端成功`
    console.log(connectionState.value)
  }
  // 收到消息
  webSocketConnection.onmessage = (ev) => {
    console.log(ev)
    const userMsgVo = JSON.parse(ev.data)
    console.log(`接收到消息${userMsgVo}`)
    ReceiveMessage.value = {
      senderName: userMsgVo.senderName,
      receiver: userMsgVo.receiverName,
      content: userMsgVo.content
    }
    console.log(ReceiveMessage.value)
    Message.value.push(ReceiveMessage.value)
  }
  window.onbeforeunload = () => webSocketConnection.close()
  return webSocketConnection
}
// const establishVideoWebSocketConnection = (peerId) => {
//   console.log('开始视频连接')
//   const webSocketConnection = new ReconnectingWebSocket(
//     `ws://192.168.124.18:8514/chat/meet/${peerId}`
//   )
//   webSocketConnection.onopen = () => {
//     //do something
//   }

//   webSocketConnection.onmessage = () => {
//     //do something
//   }

//   return webSocketConnection
// }

// const createPeerSendToWebSocketServer = () => {
//   const peer = new Peer(username.value)
//   //当peer被打开时被执行,peerId是全局唯一的
//   peer.on('open', (peerId) => {
//     console.log(`peer opend, the peerId is: ${peerId}`)
//     peer.on('close', () => {
//       console.log('peer close....')
//       //（呼叫方和接收方的ID都应该保存到服务器）
//       //此处应该发送一个JSON对象给服务器，方便判断，以下是伪代码，用于演示
//     })
//   })
//   return peer
// }
const VideoInter = () => {
  getUserMedia({
    audio: true,
    video: { width: 1280, height: 720 }
  })
    .then((userMedia) => {
      localCameraVideo.value.srcObject = userMedia
      localUserVideo.value = userMedia
      localCameraVideo.value.autoplay = true
      let call = myPeer.call(ResentUser.value, localUserVideo.value)
      console.log(call)
      call.on('stream', (remoteUserMedia) => {
        console.log('得到流')
        remoteCameraVideo.value.srcObject = remoteUserMedia
        // remoteCameraVideo.value.autoplay = true
        remoteCameraVideo.value.play()
      })
    })
    .catch((er) => {
      console.log(er)
    })
  centerDialogVisible.value = true
}
const VideoReceive = () => {
  getUserMedia({
    audio: true,
    video: { width: 1280, height: 720 }
  })
    .then((userMedia) => {
      localCameraVideo.value.srcObject = userMedia
      localCameraVideo.value.autoplay = true
      myPeer.on('call', (mediaConnection) => {
        console.log('收到call')
        mediaConnection.answer(localUserVideo.value)
        mediaConnection.on('stream', (remoteCameraStream) => {
          console.log(remoteCameraStream)
          remoteCameraVideo.value.srcObject = remoteCameraStream
          remoteCameraVideo.value.play()
          // remoteCameraStream.value.autoplay = true
        })
      })
      localCameraVideo.value.play()
      console.log('111')
    })
    .catch((er) => {
      console.log(er)
    })
  centerDialogVisible.value = true
}
onMounted(async () => {
  // 聊天websocket
  socket.value = establishWebSocketConnection(username.value)
  // 视频wensocket

  const res = await getList(username.value)
  userList.value = res.data.data
  console.log(userList.value)
  ScrolltoButtom()
})
</script>

<template>
  <div class="wrapper">
    <div class="container">
      <el-container>
        <el-aside>
          <el-scrollbar height="600px">
            <ul>
              <li v-for="item in userList" :key="item.username">
                <UserPanel
                  :logo="item.headImage"
                  :name="item.username"
                  @click="UserPanelClick(item.username)"
                />
              </li>
            </ul>
          </el-scrollbar>
        </el-aside>
        <el-main>
          <div class="content">
            <el-container>
              <el-header>
                <div class="commuHeader">
                  <h1>{{ ResentUser }}</h1>
                </div>
              </el-header>
              <el-main>
                <el-scrollbar height="350px" ref="scrollbarRef">
                  <div ref="innerRef">
                    <div
                      v-for="item in Message"
                      :key="item.content"
                      class="message"
                    >
                      <div
                        v-if="item.senderName === username"
                        style="margin-left: auto"
                      >
                        {{ item.content }}
                      </div>
                      <div v-else>{{ item.content }}</div>
                    </div>
                  </div>
                </el-scrollbar>
              </el-main>
              <el-footer>
                <div class="sendUi">
                  <el-input
                    v-model="sendMessage"
                    style="width: 750px"
                    :rows="7"
                    type="textarea"
                    placeholder="Please input"
                  />
                  <div class="btn">
                    <el-button round type="success" @click="VideoInter">
                      发起
                    </el-button>
                    <el-button round type="success" @click="VideoReceive">
                      接受
                    </el-button>
                    <el-button
                      round
                      type="success"
                      @click="sendbtn"
                      :disabled="sendDisable"
                    >
                      发送
                    </el-button>
                  </div>
                </div>
              </el-footer>
            </el-container>
          </div>
        </el-main>
      </el-container>
      <el-dialog
        v-model="centerDialogVisible"
        title="视频面试"
        width="700"
        aling-center
        ref="VedioDialog"
        draggable
      >
        <div style="height: 500px; text-align: center">
          <video
            ref="localCameraVideo"
            class="local-video"
            width="30%"
            height="30%"
            autoplay
          ></video>
          <video
            ref="remoteCameraVideo"
            class="remote-video"
            width="100%"
            height="100%"
            autoplay
          ></video>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.wrapper {
  width: 1200px;
  padding: 10px 20px;
  margin: auto;
  .el-container {
    .el-aside {
      background-color: #fff;
      border-radius: 12px;
      text-align: center;
      .el-scrollbar {
        background-color: #f8f8f8;
        ul {
          margin-block-start: 1em;
          margin-block-end: 1em;
          margin-inline-start: 0px;
          margin-inline-end: 0px;
          padding-inline-start: 10px;
          unicode-bidi: isolate;
          li {
            border-radius: 12px;
            cursor: pointer;
            background: #fff;
            transition: box-shadow 0.2s linear;
            z-index: 1;
            border: 1px;
            background: #fff;
            margin-bottom: 10px;
          }
        }
      }
    }
    .el-main {
      padding: 0;
      border-radius: 12px;
      .content {
        margin-left: 20px;
        background-color: #fff;
        height: 600px;
        border-radius: 12px;
        padding: 10px 5px;
        .el-container {
          .el-header {
            display: flex;
            padding: 20px 10px;
            border-bottom: 1px solid;
            max-height: 50px;
            align-items: center;
            justify-content: center;
            .commuHeader {
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
          .el-main {
            background-color: #ffffff;
            .el-scrollbar {
              .message {
                margin-bottom: 20px;
                display: flex;
                padding: 5px 10px;
                div {
                  border-radius: 12px;
                  background-color: #5df362;
                  min-width: 50px;
                  font-size: 20px;
                  text-align: center;
                  padding: 5px 10px;
                }
              }
            }
          }
          .el-footer {
            border-top: 1px solid;
            padding-left: 0;
            .sendUi {
              padding: 5px 0px 20px 5px;
              display: flex;
              .btn {
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                padding-left: 20px;
                align-items: center;
              }
            }
          }
        }
      }
    }
  }
  .el-dialog {
    .local-video {
      position: absolute;
      z-index: 2;
      border-radius: 0.625rem;
      top: 1rem;
      left: 0.3125rem;
    }
    .remote-video {
      position: absolute;
      border-radius: 0.625rem;
      width: 100%;
      height: 100%;
      left: 0.3125rem;
    }
  }
}
</style>
